package com.atguigu.lease.app.interceptor;

import com.atguigu.lease.common.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class WebAppAuthInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<Map<String,Object>> THREAD_LOCAL = new ThreadLocal<>();

    public static Long getUserId(){
        return Long.parseLong(THREAD_LOCAL.get().get("userId").toString());
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("ACCESS_TOKEN");
        Map<String, Object> map = JwtUtil.parseJwt(token);
        map.put("nickname" , map.get("name"));
        THREAD_LOCAL.set(map);

        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }


}
